package com.jingbit.ai.dbase;

import android.content.Context;
import android.os.AsyncTask;

import com.jingbit.ai.helper.Logger;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class DBInstaller extends AsyncTask<Object, Integer, File> {
	private Context context;

	public DBInstaller(Context context) {
		super();
		this.context = context;
	}

	@Override
	protected File doInBackground(Object... params) {
		Logger.log(this, "doInBackground", params[0]);
		File dbFile=(File)params[0];
		int dbRaw=Integer.parseInt(params[1].toString());
		if (dbFile.exists()) {
			return dbFile;
		}
		int readCount = 0, readSum = 0;
		byte[] buffer = new byte[1024*10];
		InputStream inStream;
		OutputStream outStream;
		try {
			inStream = context.getResources().openRawResource(dbRaw);
			outStream = new FileOutputStream(dbFile);
			BufferedInputStream b = new BufferedInputStream(inStream);
			while ((readCount = b.read(buffer)) != -1) {
				// readCount = b.read(buffer);
				outStream.write(buffer, 0, readCount);
				readSum = readSum + readCount;
				publishProgress(readSum);
			}
			outStream.flush();
			outStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return dbFile;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected void onPostExecute(File result) {
		super.onPostExecute(result);
		DBManager.openOrCreate(result);
	}
}
